
// Created by hps on 24-4-1.

#include "FileManager.h"

namespace hps {

FileManager::FileManager() {
    m_parentItem = nullptr;
    init();
    loadStyle(this, "/home/hps/hps/Markdown-cpp/src/data/style/FileManagerStyle.qss");
}
void FileManager::init() {
    this->setObjectName("FileManager");
    this->setContentsMargins(0, 0, 0, 0);
}

void FileManager::loadNoteBook(QString _dir, QTreeWidgetItem *parentItem) {
    m_parentItem = parentItem;
    m_dir = _dir;
    if (! isDirectoryExists(_dir.toStdString())) {
        throw std::runtime_error("Folder does not exist");
    }
    QDir dir(_dir);
    QFileInfoList fileInfoList = dir.entryInfoList(QDir::Dirs | QDir::Files | QDir::NoDotAndDotDot);

    for (const QFileInfo &fileInfo: fileInfoList) {
        TreeWidgetItem *item = new TreeWidgetItem(parentItem, _dir.toStdString(), fileInfo.fileName().toStdString());
        m_items.push(item);
        QVariant pathData = QVariant(fileInfo.path() + "/" + fileInfo.fileName());
        item->setData(0, Qt::UserRole, pathData);
        item->setText(0, fileInfo.fileName());

        if (fileInfo.isDir()) {
            item->setIsDir(true);
            item->setIcon(0, QIcon("/home/hps/hps/Markdown-cpp/src/data/icon/follder.svg"));
            loadNoteBook(fileInfo.filePath(), item); // 递归添加子目录
        } else {
            item->setIcon(0, QIcon("/home/hps/hps/Markdown-cpp/src/data/icon/file.svg"));
        }
    }
}
void FileManager::freeItems() {
    while (! m_items.empty()) {
        auto p = m_items.top();
        m_items.pop();
        delete p;
    }
    m_hasLoadBook = false;
}

} // hps
